import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import baidu from '@/views/baidu/index.vue'
import login from '@/views/login/index.vue'
import layout from '@/layout/index.vue'
import usersRoutes from './modules/user'
import localCache from '@/utils/localCache'

const routes: Array<RouteRecordRaw> = [

  {
    path: '/baidu',
    name: 'baidu',
    component: baidu
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/',
    component: layout,
    meta: { title: '首页', requiresAuth: true },
    children: [
      usersRoutes
    ]
  }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from) => {
  const loginInfo = localCache.getCache('USERINFO')
  if (to.meta.requiresAuth && !loginInfo) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再来
      query: { redirect: to.fullPath }
    }
  }
})

export default router
